<?php
session_start();
$lib_dir = str_ireplace("ajax", "lib", dirname(__FILE__));
require_once $lib_dir.'/config.php';
require_once $lib_dir.'/facebook.php';
require_once $lib_dir.'/util.php';
require_once $lib_dir.'/friend.php';
require_once $lib_dir.'/friends.php';

    if(!isset($_SESSION['fb_session']) && !isset($_REQUEST['signed_request']) ){
        print('{ "error": "Invalid request is detected. Program abort." }');
        exit();
    }
    
    $facebook = new Facebook(array(
        'appId' => FB_APP_ID,
        'secret' => FB_APP_SECRET
    ));
    
    if(isset($_SESSION['fb_session'])){
        $facebook->setSession($_SESSION['fb_session']);        
    }
    
    $session = $facebook->getSession();
    
    if($session){
        try{
            //JSON encoding
            $json .= '{"signed_request" : "'.generateSignedRequest($session).'"}';
            
            //return output
            print $json;
                
        } catch (FacebookApiException $e){

            print('{"error":"'."Facebook error:".$e->getMessage().'"}');
        }
    }
//}